package com.web.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author lenovo
 * @Description
 * @Date2025-3-11 17:20
 *  OSS文件上传工具类
 */
public class OssUtil {
    private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "LTAI5tLz3R79zyCGQBCR3hGJ";
    private static String accessKeySecret = "f2woFFCP9cfm99RuNxXGCYs2v2w1QN";
    private static String bucketName = "lyw-demo";
    //目录名
    public static String dir = "lywdemo";

    /**
     * 文件上传
     * @param inputStream
     * @param fileName
     */
    public static void upload(InputStream inputStream, String fileName){
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        oss.putObject(bucketName,dir +"/"+ fileName,inputStream);
        oss.shutdown();
    }

    /**
     * 获得文件URL
     * @param fileName
     * @return
     */
    public static String getURL(String fileName){
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //设置过期时间
        LocalDateTime time = LocalDateTime.now().plusDays(100);
        Date expiration = Date.from(time.atZone( ZoneId.systemDefault()).toInstant());
        URL url = oss.generatePresignedUrl(bucketName, dir +"/"+ fileName, expiration);
        oss.shutdown();
        return url.toString();
    }

    public static void main(String[] args) throws FileNotFoundException {
        upload(new FileInputStream("D:\\Users\\lenovo\\1.jpg"),"1.jpg");
        System.out.println(getURL("1.jpg"));
    }
}
